/**
 * 全部门店列表弹窗
 */
import React, { useState, useMemo } from 'react';
import { X, Search, Download, TrendingUp, TrendingDown, ArrowUpDown } from 'lucide-react';

interface StoreRow {
  rank: number;
  name: string;
  visitors: string;
  rate: string;
  address?: string;
  sales?: number;
  orders?: number;
}

interface StoreListModalProps {
  isOpen: boolean;
  onClose: () => void;
  stores: StoreRow[];
  onStoreClick?: (store: StoreRow) => void;
}

const StoreListModal: React.FC<StoreListModalProps> = ({ isOpen, onClose, stores, onStoreClick }) => {
  const [searchKeyword, setSearchKeyword] = useState('');
  const [sortField, setSortField] = useState<'rank' | 'visitors' | 'rate'>('rank');
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('asc');
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 10;

  // 筛选和排序数据
  const filteredAndSortedStores = useMemo(() => {
    let result = [...stores];

    // 搜索筛选
    if (searchKeyword) {
      result = result.filter(store =>
        store.name.toLowerCase().includes(searchKeyword.toLowerCase())
      );
    }

    // 排序
    result.sort((a, b) => {
      let aValue: number;
      let bValue: number;

      if (sortField === 'rank') {
        aValue = a.rank;
        bValue = b.rank;
      } else if (sortField === 'visitors') {
        aValue = parseFloat(a.visitors.replace('w+', ''));
        bValue = parseFloat(b.visitors.replace('w+', ''));
      } else {
        aValue = parseFloat(a.rate.replace('%', ''));
        bValue = parseFloat(b.rate.replace('%', ''));
      }

      return sortOrder === 'asc' ? aValue - bValue : bValue - aValue;
    });

    return result;
  }, [stores, searchKeyword, sortField, sortOrder]);

  // 分页
  const totalPages = Math.ceil(filteredAndSortedStores.length / pageSize);
  const paginatedStores = filteredAndSortedStores.slice(
    (currentPage - 1) * pageSize,
    currentPage * pageSize
  );

  const getRankBadge = (rank: number) => {
    const baseClasses = "w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold text-white";
    switch (rank) {
      case 1:
        return `${baseClasses} bg-yellow-500`;
      case 2:
        return `${baseClasses} bg-gray-400`;
      case 3:
        return `${baseClasses} bg-orange-400`;
      default:
        return `${baseClasses} bg-blue-500`;
    }
  };

  const getRateColor = (rate: string) => {
    const numRate = parseInt(rate.replace('%', ''));
    if (numRate >= 30) return 'text-red-500 bg-red-50';
    if (numRate >= 20) return 'text-orange-500 bg-orange-50';
    if (numRate >= 10) return 'text-blue-500 bg-blue-50';
    return 'text-green-500 bg-green-50';
  };

  const handleSort = (field: 'rank' | 'visitors' | 'rate') => {
    if (sortField === field) {
      setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
    } else {
      setSortField(field);
      setSortOrder('asc');
    }
  };

  const exportData = () => {
    const csvContent = [
      ['排名', '门店名称', '访客数', '日增率'],
      ...filteredAndSortedStores.map(store => [
        store.rank.toString(),
        store.name,
        store.visitors,
        store.rate
      ])
    ].map(row => row.join(',')).join('\n');

    const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', `门店列表_${new Date().toISOString().split('T')[0]}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  if (!isOpen) return null;

  return (
    <div
      className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4"
      onClick={onClose}
    >
      <div
        className="bg-white rounded-2xl shadow-2xl w-full max-w-6xl max-h-[90vh] overflow-hidden flex flex-col animate-in fade-in zoom-in duration-200"
        onClick={(e) => e.stopPropagation()}
      >
        {/* 头部 */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200 bg-gradient-to-r from-blue-50 to-indigo-50">
          <div className="flex-1">
            <h3 className="text-2xl font-bold text-gray-800 mb-1">全部门店列表</h3>
            <p className="text-sm text-gray-600">
              共 <span className="font-semibold text-blue-600">{filteredAndSortedStores.length}</span> 家门店
            </p>
          </div>
          <button
            onClick={onClose}
            className="p-2 hover:bg-white/80 rounded-lg transition-all hover:scale-110 active:scale-95"
            aria-label="关闭"
          >
            <X size={22} className="text-gray-600" />
          </button>
        </div>

        {/* 搜索和筛选栏 */}
        <div className="p-4 border-b border-gray-200 bg-gray-50">
          <div className="flex items-center gap-4">
            <div className="flex-1 relative">
              <Search size={18} className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" />
              <input
                type="text"
                placeholder="搜索门店名称..."
                value={searchKeyword}
                onChange={(e) => {
                  setSearchKeyword(e.target.value);
                  setCurrentPage(1);
                }}
                className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
            <button
              onClick={exportData}
              className="flex items-center gap-2 px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors"
            >
              <Download size={18} />
              导出数据
            </button>
          </div>
        </div>

        {/* 表格内容 */}
        <div className="overflow-y-auto flex-1 scrollbar-thin">
          <table className="w-full">
            <thead className="bg-gray-50 sticky top-0">
              <tr>
                <th className="px-6 py-4 text-left">
                  <button
                    onClick={() => handleSort('rank')}
                    className="flex items-center gap-2 text-xs font-semibold text-gray-600 uppercase tracking-wider hover:text-gray-900"
                  >
                    排名
                    {sortField === 'rank' && (
                      sortOrder === 'asc' ? <TrendingUp size={14} /> : <TrendingDown size={14} />
                    )}
                    {sortField !== 'rank' && <ArrowUpDown size={14} className="text-gray-400" />}
                  </button>
                </th>
                <th className="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                  门店名称
                </th>
                <th className="px-6 py-4 text-right">
                  <button
                    onClick={() => handleSort('visitors')}
                    className="flex items-center gap-2 text-xs font-semibold text-gray-600 uppercase tracking-wider hover:text-gray-900 ml-auto"
                  >
                    访客数
                    {sortField === 'visitors' && (
                      sortOrder === 'asc' ? <TrendingUp size={14} /> : <TrendingDown size={14} />
                    )}
                    {sortField !== 'visitors' && <ArrowUpDown size={14} className="text-gray-400" />}
                  </button>
                </th>
                <th className="px-6 py-4 text-right">
                  <button
                    onClick={() => handleSort('rate')}
                    className="flex items-center gap-2 text-xs font-semibold text-gray-600 uppercase tracking-wider hover:text-gray-900 ml-auto"
                  >
                    日增率
                    {sortField === 'rate' && (
                      sortOrder === 'asc' ? <TrendingUp size={14} /> : <TrendingDown size={14} />
                    )}
                    {sortField !== 'rate' && <ArrowUpDown size={14} className="text-gray-400" />}
                  </button>
                </th>
                <th className="px-6 py-4 text-right text-xs font-semibold text-gray-600 uppercase tracking-wider">
                  操作
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {paginatedStores.length === 0 ? (
                <tr>
                  <td colSpan={5} className="px-6 py-12 text-center text-gray-500">
                    没有找到匹配的门店
                  </td>
                </tr>
              ) : (
                paginatedStores.map((store, index) => (
                  <tr
                    key={index}
                    onClick={() => onStoreClick && onStoreClick(store)}
                    className={`hover:bg-gradient-to-r hover:from-blue-50/50 hover:to-purple-50/50 transition-all duration-200 ${
                      onStoreClick ? 'cursor-pointer' : ''
                    }`}
                  >
                    <td className="px-6 py-4">
                      <div className={getRankBadge(store.rank)}>
                        {store.rank}
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="text-sm font-semibold text-gray-900">{store.name}</div>
                      {store.address && (
                        <div className="text-xs text-gray-500 mt-1">{store.address}</div>
                      )}
                    </td>
                    <td className="px-6 py-4 text-right">
                      <div className="text-sm font-bold text-gray-900">{store.visitors}</div>
                    </td>
                    <td className="px-6 py-4 text-right">
                      <div className={`inline-flex items-center px-3 py-1 rounded-lg text-xs font-bold ${getRateColor(store.rate)}`}>
                        {store.rate}
                      </div>
                    </td>
                    <td className="px-6 py-4 text-right">
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          onStoreClick?.(store);
                        }}
                        className="px-3 py-1 text-sm text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                      >
                        查看详情
                      </button>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        {/* 分页和底部 */}
        <div className="p-4 border-t border-gray-200 bg-gray-50">
          <div className="flex items-center justify-between">
            <div className="text-sm text-gray-600">
              显示第 {(currentPage - 1) * pageSize + 1} - {Math.min(currentPage * pageSize, filteredAndSortedStores.length)} 条，
              共 {filteredAndSortedStores.length} 条记录
            </div>
            <div className="flex items-center gap-2">
              <button
                onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
                disabled={currentPage === 1}
                className="px-3 py-1 border border-gray-300 rounded-lg text-sm disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-100"
              >
                上一页
              </button>
              <div className="flex items-center gap-1">
                {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                  let pageNum;
                  if (totalPages <= 5) {
                    pageNum = i + 1;
                  } else if (currentPage <= 3) {
                    pageNum = i + 1;
                  } else if (currentPage >= totalPages - 2) {
                    pageNum = totalPages - 4 + i;
                  } else {
                    pageNum = currentPage - 2 + i;
                  }
                  return (
                    <button
                      key={pageNum}
                      onClick={() => setCurrentPage(pageNum)}
                      className={`px-3 py-1 rounded-lg text-sm ${
                        currentPage === pageNum
                          ? 'bg-blue-500 text-white'
                          : 'border border-gray-300 hover:bg-gray-100'
                      }`}
                    >
                      {pageNum}
                    </button>
                  );
                })}
              </div>
              <button
                onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
                disabled={currentPage === totalPages}
                className="px-3 py-1 border border-gray-300 rounded-lg text-sm disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-100"
              >
                下一页
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default StoreListModal;



















